package y23.Oct;

import java.util.concurrent.PriorityBlockingQueue;

class Timer {
    static class Task implements Comparable<Task> {
        private Runnable command;
        private long time;

        public Task(Runnable command, long time) {
            this.command = command;
            this.time = System.currentTimeMillis() + time;
        }

        public void run() {
            command.run();
        }

        @Override
        public int compareTo(Task o) {
            return (int) (time - o.time);
        }
    }
    private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue();
    private Object mailBox = new Object();
    class Worker extends Thread{
        @Override
        public void run() {
            while (true) {
                try {
                    Task task = queue.take();
                    long curTime = System.currentTimeMillis();
                    if (task.time > curTime) {
                        queue.put(task);
                        synchronized (mailBox) {
                            mailBox.wait(task.time - curTime);
                        }
                    } else {
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
    }
    public Timer() {
        Worker worker = new Worker();
        worker.start();
    }
    public void schedule(Runnable command, long after) {
        Task task = new Task(command, after);
        queue.offer(task);
        synchronized (mailBox) {
            mailBox.notify();
        }
    }
    public static void main(String[] args) {
        Timer timer = new Timer();
        Thread command = new Thread(()->{
                System.out.println("Hello World");

            });
        timer.schedule(command,1000);
        timer.schedule(command,3000);
        timer.schedule(command,5000);
        timer.schedule(command,7000);
    }
}


public class Test34 {
}
